<!DOCTYPE html>
<html lang="en">
    <head>
        <title>nancy oauth2</title>
        <meta charset="UTF-8">
        <script type="text/javascript"  src="http://cdn.bootcss.com/jquery/3.0.0-rc1/jquery.min.js"></script>
    </head>
    <body>
        <h1>hello nancy oauth2</h1>
        <input type="button" id="btn1" value="登陆">
        <input type="button" id="btn2" value="获取数据">
        <input type="button" id="btn3" value="登出">
        
        <div>
            <div id="divText">显示数据</div>
        </div>
        
        <script>
            $(document).ready(function() {
                var token = "";
               
                $("#btn1").click(function(event) {

                     var data = {
                        client_id: 'rwecho',
                        client_secret: 'rwecho',
                        redirect_uri: 'www.baidu.com',
                        grant_type: 'authorization_code',
                    };
                     $("#divText").text("");
                    $.post('http://localhost:12335/auth/token', data, function(data, textStatus, xhr) {
                        /*optional stuff to do after success */
                        $("#divText").text(JSON.stringify(data));
                        token = data.accessToken;
                    });
                });

               $("#btn2").click(function(event) {
                    $("#divText").text("");
                    
                    $.ajax({
                        url: 'http://localhost:12335',
                        type: 'GET',
                        dataType: 'text',
                        beforeSend:function(xhr) {
                            xhr.setRequestHeader('Authorization','bearer '+token);
                        },
                        data:{},
                        xhrFields: {
                            withCredentials: true
                        }
                    })
                    .done(function(data) {
                        $("#divText").text(JSON.stringify(data));
                        console.log("success");
                    })
                    .fail(function() {
                        console.log("error");
                    })
                    .always(function() {
                        console.log("complete");
                    });
                    
                   
                });

                $("#btn3").click(function(event) {
                    $("#divText").text("");
                });
            });
        </script>
    </body>
</html>